package com.i1510.jobhandler;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.i1510.service.IHsyService;
import com.i1510.service.IJstService;
import com.i1510.util.JstApiUtils;
import com.i1510.util.JstStatusUtil;
import com.i1510.util.SignUtils;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.URL;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 *
 * XxlJob开发示例（Bean模式）
 *
 * 开发步骤：
 *      1、任务开发：在Spring Bean实例中，开发Job方法；
 *      2、注解配置：为Job方法添加注解 "@XxlJob(value="自定义jobhandler名称", init = "JobHandler初始化方法", destroy = "JobHandler销毁方法")"，注解value值对应的是调度中心新建任务的JobHandler属性的值。
 *      3、执行日志：需要通过 "XxlJobHelper.log" 打印执行日志；
 *      4、任务结果：默认任务结果为 "成功" 状态，不需要主动设置；如有诉求，比如设置任务结果为失败，可以通过 "XxlJobHelper.handleFail/handleSuccess" 自主设置任务结果；
 *
 */

@Component
public class JstJob {
    private static Logger logger = LoggerFactory.getLogger(JstJob.class);



    @Value("${jst.api.order.upload}")
    String jstApiOrderUpload;

    @Value("${jst.appKey}")
    String jstAppKey;

    @Value("${jst.appSecret}")
    String jstAppSecret;

    @Autowired
    private IHsyService iHsyService;
    @Autowired
    private IJstService iJstService;

    // TOP服务地址，正式环境需要设置为https://openapi.jushuitan.com
//    private static final String serverUrl = "https://openapi.jushuitan.com/open/jushuitan/orders/upload";
//    private static final String appKey = "97989cda6d0d4ad3b72cd3ca5f264667"; // 可替换为您的应用的appKey
//    private static final String appSecret = "1cccc2e208954df4aed5a0bc78fd7262"; // 可替换为您的应用的appSecret
//    private static final String accessToken = "90aafb5ed7b64b41b85ba6b9aa820131"; // 必须替换为授权得到的真实有效accessToken
    private static final String accessToken = "a58dbba593284654882664be41bacbea"; // 必须替换为授权得到的真实有效accessToken

    private static final String SIGN_METHOD_MD5 = "md5";

    /**
     * JST订单上传
     */
    @XxlJob("jstOrderUploadJobHandler")
    public void jstOrderUploadJobHandler() throws Exception {
        try {
            XxlJobHelper.log("【JST订单上传】任务开始:"+jstApiOrderUpload);


            Map params = new HashMap();

            String jobParam = XxlJobHelper.getJobParam();
            XxlJobHelper.log("【任务参数】：{}", jobParam);
            if (StrUtil.isNotBlank(jobParam)) {
                JSONObject jsonObject = JSONObject.parseObject(jobParam);
                params.put("startTime",jsonObject.getString("sdate"));
                params.put("endTime",jsonObject.getString("edate"));
            }else{
                params.put("startTime",DateUtil.yesterday().toString("yyyy-MM-dd")+" 00:00:00");
                params.put("endTime",DateUtil.today()+" 23:59:59");
            }


            List<Map> list  = iHsyService.getSendJstOrderList(params);
            StringBuffer sb = new StringBuffer();
            for(int j=0;j<list.size();j++){
                //获取订单
                Map map = list.get(j);
                //获取订单明细
                Map pi = new HashMap();
                pi.put("orderId",map.get("orderId").toString());
                List<Map> items = iHsyService.getOrderDetailList(pi);

                if(!"X".equals(JstStatusUtil.getHsy2Jst(map.get("orderStatus").toString()))
                    && (!"0001-01-01 00:00:00".equals(map.get("payDate").toString()))
                ){
                    //发送到JST
                    String rtn = sendJstOrder(map,items);
                    XxlJobHelper.log("【上传订单:"+map.get("orderId").toString()+"】返回消息:"+rtn.toString());
                    JSONObject rtnObj = JSONObject.parseObject(rtn);

                    if(0 == rtnObj.getInteger("code")){

                        JSONArray datas = rtnObj.getJSONObject("data").getJSONArray("datas");
                        //更新状态
                        Map p = new HashMap();
                        p.put("orderId",map.get("orderId").toString());
                        p.put("uploadOrder",datas.getJSONObject(0).get("o_id"));
                        p.put("uploadDate",DateUtil.now());
                        p.put("uploadChannel","JST");
                        p.put("uploadStatus",map.get("orderStatus").toString());//上传时hsy的订单状态
                        iHsyService.updateOrderPo4Jst(p);
                    }else{
                        sb.append("X");
                        XxlJobHelper.log("【上传订单:"+map.get("orderId").toString()+"】任务失败"+rtn.toString());
                    }
                }else{
                    XxlJobHelper.log("【上传订单:"+map.get("orderId").toString()+"】返回消息:状态：【"+map.get("orderStatus").toString()+"】不上传");
                }


                //JST:一秒内调用次数是否超过5次，1000ms内调用次数最大不超过5
                TimeUnit.SECONDS.sleep(1);

            }



            XxlJobHelper.log("【JST订单上传】任务结束:"+JSONObject.toJSON(list));
            if(sb.indexOf("X") < 0){
                XxlJobHelper.handleSuccess();
            }else{
                XxlJobHelper.handleFail();
            }

        } catch (Exception e) {
            XxlJobHelper.handleFail(e.getMessage());
        } finally {

        }


    }

    /**
     * @author rambo
     * @date 2022-11-29 09:35
     * @desc 发送给JST
     * @param
     * @return
     */
    private  String sendJstOrder(Map map,List<Map> list) throws IOException {

        Map<String, String> params = new HashMap<String, String>();
        // 公共参数
        params.put("app_key", jstAppKey);

        //获取jst token
        List<Map> tokenList = iJstService.getToken(params);
        if(tokenList.size() == 1){
            params.put("access_token", tokenList.get(0).get("access_token").toString());
        }else{
            params.put("access_token", accessToken);
        }
        params.put("timestamp", String.valueOf(System.currentTimeMillis() / 1000));
        params.put("version", "2");
        params.put("charset", "utf-8");
        // 业务参数
        JSONArray bizs = new JSONArray();
        Map<String, Object> biz = new HashMap<>();
        //biz.put("wms_co_id","");//分仓编号
        biz.put("shop_id",13698196);//店铺编号
        biz.put("so_id",map.get("orderId").toString());//自研商城系统订单号
        biz.put("order_date",map.get("orderDate").toString());//订单日期
        biz.put("shop_status",JstStatusUtil.getHsy2Jst(map.get("orderStatus").toString()));//自研商城系统订单状态
        biz.put("shop_buyer_id",map.get("username").toString());//买家帐号
        biz.put("receiver_state",map.get("provinceName").toString());//
        biz.put("receiver_city",map.get("cityName").toString());//
        biz.put("receiver_district",map.get("regionName").toString());//
        biz.put("receiver_address",map.get("address").toString());//
        biz.put("receiver_name",map.get("shipTo").toString());//
        biz.put("receiver_phone",map.get("TelPhone").toString());//
        biz.put("receiver_mobile",map.get("TelPhone").toString());//手机
        biz.put("pay_amount", NumberUtil.toBigDecimal((map.get("payCharge").toString())));//应付金额
        biz.put("freight",NumberUtil.toBigDecimal((map.get("postagePrice").toString())));//运费
//        biz.put("buyer_message","买家留言");//买家留言
//        biz.put("remark","卖家备注");//卖家备注

        //商品明细
        JSONArray items = new JSONArray();
        for(int j=0;j<list.size();j++){
            Map mi = list.get(j);
            //商品明细
            Map<String, Object> item = new HashMap<>();
            item.put("sku_id",mi.get("sKU").toString());
            item.put("shop_sku_id",mi.get("skuId").toString());
            item.put("amount",NumberUtil.toBigDecimal((mi.get("itemListPrice").toString())));
            item.put("base_price",NumberUtil.toBigDecimal((mi.get("costPrice").toString())));
            item.put("qty",NumberUtil.parseInt(mi.get("quantity").toString()));
            item.put("name",mi.get("sKU").toString());
            item.put("outer_oi_id",map.get("orderId").toString());
            items.add(item);

        }

        biz.put("items",items);
        //付款明细
        JSONObject payObj = new JSONObject();
        payObj.put("outer_pay_id",map.get("orderId").toString());
        payObj.put("pay_date",map.get("payDate").toString());
        payObj.put("payment",map.get("orderStatus").toString());
        payObj.put("seller_account","1234567890");
        payObj.put("buyer_account",map.get("username").toString());
        payObj.put("amount",NumberUtil.toBigDecimal((map.get("amount").toString())));
        biz.put("pay",payObj);
        bizs.add(biz);
        System.out.println(JSONObject.toJSON(bizs).toString());
        //System.exit(0);
        params.put("biz", JSONObject.toJSON(bizs).toString());
        // 签名参数
        params.put("sign", JstApiUtils.signTopRequest(params, jstAppSecret, SIGN_METHOD_MD5));
        // 调用API
        return JstApiUtils.callApi(new URL(jstApiOrderUpload), params);
    }


    public void init(){
        logger.info("init");
    }
    public void destroy(){
        logger.info("destroy");
    }


}
